package com.labbit.platform.commons.interceptor;

import com.labbit.platform.commons.properties.CommonProperties;
import com.labbit.platform.commons.session.SessionUtils;
import com.labbit.platform.commons.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录拦截器
 */
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

    /**
     * 访问时间
     */
    private ThreadLocal<Long> threadLocalTime = new ThreadLocal<>();

    private CommonProperties commonProperties = SpringContextHolder.getBean(CommonProperties.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        response.setContentType("application/json; charset=utf-8");
        if(HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            return false;
        }
        Long startTime = System.nanoTime();
        threadLocalTime.set(startTime);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        log.info("Request start, id: [{}], url: {}, method: {}", startTime, url, method);
        // 验证是否开启登录和过滤白名单
        if (!commonProperties.getEnableLoginValid() || commonProperties.getLoginWhiteList().contains(request.getRequestURI())) {
            return true;
        }
        //验证登录信息
        SessionUtils.verifyLogin();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        Long startTime = threadLocalTime.get();
        Long endTime = System.nanoTime();
        log.info("Request end, id: [{}], 访问耗时：{} 秒", startTime, (endTime - startTime) / 1000000000.0);
    }

}
